<template>
<div class="wrapper">
  <BaseHeader></BaseHeader>
  
  <Search style="border: 1px red solid;"></Search>
  
  <div class="banner-index">
    <!-- 左边分类 
    <div class="nav_left">
      <div class="sidenav_destination">
        <ul class="destination_list">
          <li class v-for="(menu, index) in cateList" :key="index" @click="goGoodsList(menu.id, menu.fatherid)" v-show="menu.orders < 300">
            <h3 class="destination_col" v-if="menu.fatherid == null">
              {{ menu.name }}
            </h3>
            <h4 class="destination_col" v-else>
              <a href="javascript:void(0)">{{ menu.name }}</a>
            </h4>
          </li>
        </ul>
      </div>
    </div>-->
    
    <!-- 右边分类 
    <div class="banner-wrap">
      <div class="element" v-for="(banner, index) in banners" :key="index" >
        <img :src="pictureUrl(banner.pictureUrl)" @error="imgErrorHandler(index)" @click="goList(banner.linkUrl)" :alt="banner.goodsName" v-if="!imgError[index] && banner.pictureUrl"/>
      </div>
    </div>
    -->

    <div class="banner_right" style="border: 1px red solid;">
      <div v-for="(menu, index) in cateList" :key="index" class="banner-main">
        <div class="title"> {{ menu.name }} </div>
        <div class="banner-wrap">
          <div class="element" v-for="(item, colIndex) in menu.children" :key="colIndex" @click="goGoodsList(item.id, item.fatherid)">
            <img class="image" :src="pictureUrl(item.pictureUrl)" @error="imgErrorHandler(colIndex)" ></img>
            <div class="name">{{ item.name }}</div>
          </div>
        </div>
      </div>
    </div>
  </div>

  <BaseFooter style="border: 1px red solid;"></BaseFooter>
</div>
</template>

<script>
import { staticUrl } from '@/plugins/request';
import storage from "@/plugins/storage";
import Search from "@/components/Search";
import {
  findBanners,
  menuCategories
} from "@/api/index.js";
export default {
  name: "IndexN",
  data() {
    return {
      banners: [],
      bannerIndex: 0,
      cateList: [],
      imgError: [],
      categoryIndex: -1,
      autoplay: true
    }
  },
  computed: {
    goodsPanelWidth() {
      if (this.categoryIndex > -1) {
        const goodsCount = [] //this.categories[this.categoryIndex].goodsList.length
        if (goodsCount > 0) {
          let columns = Math.floor(goodsCount / 6)
          if (goodsCount % 6 > 0) columns++
          if (columns > 4) columns = 4
          return columns * 248
        }
      }
    },
  },
  mounted() {
    var category = localStorage.getItem("category");
    var category_expiration_time = localStorage.getItem("category_expiration_time");
    if ( category && category_expiration_time && new Date() < category_expiration_time) {
      // 如果缓存过期，则获取最新的信息 JSON.parse(category); 
      this.cateList = this.buildTree(JSON.parse(category));
    } else {
      this.getCate();
    }
    this.handleFindBanners();
  },
  methods: {
    // 导航分类
    getCate() {
      // 获取分类数据
      if (this.hover) return false;
      menuCategories().then((res) => {
        if (res.success) {
          this.cateList = this.buildTree(res.result);
          console.info(this.cateList);
          // 过期时间
          var expirationTime = new Date().setHours(new Date().getHours() + 1);
          // 存放过期时间
          localStorage.setItem("category_expiration_time", expirationTime); 
          // 存放分类信息
          localStorage.setItem("category", JSON.stringify(res.result));
        }
      });
    },

    buildTree(data) {
      // 创建一个映射表，用于快速查找节点
      const map = new Map();
      // 初始化每个节点的 children 数组
      data.forEach(item => {
        map.set(item.id, { ...item, children: [] });
      });
  
      // 构建树形结构
      let tree = [];
      data.forEach(item => {
        if (item.fatherid === null) {
          // 如果 parentId 为 null，说明是顶层节点
          tree.push(map.get(item.id));
        } else {
          // 否则，找到父节点，并将当前节点添加到父节点的 children 中
          const parent = map.get(item.fatherid);
          if (parent) {
            parent.children.push(map.get(item.id));
          }
        }
      });
      // var objJSONString = JSON.parse(JSON.stringify(tree));
      // console.log(objJSONString)
      return tree;
    },

    /**
     * 菜单打开
     * @param id 
     */
    goGoodsList(id, secondId, firstId) {
      console.info(id, secondId, firstId, (!secondId ))
      if ((typeof firstId == "undefined" || !firstId) && (typeof secondId == "undefined" || !secondId)) {
        return
      }
      // 分类共有三级，传全部分类过去
      const arr = [firstId, secondId, id];
      if (!arr[1]) {
        arr.splice(0, 2);
      }
      if (!arr[0]) {
        arr.shift();
      }
      let routerUrl = this.$router.resolve({
        path: "/goodsList",
        query: {
          categoryId: arr.toString()
        },
      });
      window.open(routerUrl.href, "_GoodsList");
    },

    /**
     * 
     * @param banner 
     */
    goList(path) {
      let params = path.split(",");
      if (params.length > 1) {
        this.goGoodsList(params[0], params[1]) 
      } else {
        window.open(path, "_GoodsDetail");
      }
    },

    /**
     * 获取推广数据
     * @param banner 
     */
    handleFindBanners() {
      // uni.showLoading({
      // 	title: '加载中...',
      // 	mask: true
      // })
      findBanners().then(res => {
        this.banners = res.result;
        var l = this.banners.length;
        var k = 12 - l;
        for (var i = 0; i < k; i++) {
          this.banners.push = {
            id: ''
          }
        }
        k = this.banners.length;
        for (var i = 0; i < k; i++) {
          this.imgError.push(false)
        }
        //console.log(this.imgError);
      }).catch(e => {
        console.log('/banner/slides 请求错误', e)
      })
    },

    pictureUrl(path) {
      if (!path) {
        return '';
      } else if (path.indexOf("photos/") >= 0 || path.indexOf("temp/") >= 0 || path.indexOf("menu/") >= 0) {
        return staticUrl + "/" + path
      } else {
        return path
      }
    },

    imgErrorHandler(index) {
      this.imgError[index] = true;
      //console.info("imgErrorHandler@@@", index, this.imgError[index]);
    }
  },
  components: {
    Search
  },
}
</script>

<style lang="scss">
@import '~@/assets/font/iconfont0/iconfont.css';
@import '~@/assets/font/symbol/iconfont.css';
@import '~@/components/cruise/css/detail.css';
@import '~@/components/cruise/css/core.css';

body {
  overflow-x: hidden;
  overflow-y: auto;
  background-color: #fff;
  height: 100%;
  margin: 0;
}

.wrapper {
  min-height: 100%;
  margin-bottom: -50px;
}

.banner-index {
  width: $page-width;
  margin: 0 auto;

  /** 右边  - 309px */
  .banner_right {
    width: calc(100%);
    float: right;
    margin-top: 20px;
    margin-bottom: 30px;

    .banner-main {
      width: 1120px;
      margin: 0 auto;
      position: relative;
      color: #222;
    }

    .title {
      font-size: 18px;
      font-weight: 600;
      padding: 5px 15px; 
      font-weight: 600; 
      margin: 40px 0 15px 0;
    }

    .title::before {
      content: " ";
      width: 6px;
      height: 6px;
      background-color: #fe1758;
      left: 2px;
      top: 11px;
      position: absolute;
    }

    :first-child .title{
      margin: 5px 0 15px 0;
    }
  }

  .banner-wrap {
    display: grid;
    grid-template-columns: repeat(5, 216px);
    grid-row-gap: 9px;
    grid-column-gap: 9px;
    cursor: pointer;

    .element {
      background-color: #FEFCF0;
      height: 230px;
      color: #000;
      // 给项目设置圆角
      border-radius: 5px;
      // 给项目设置变大的速度
      transition: all 0.5s;
      // 给项目设置阴影
      box-shadow: 3px 3px 12px #ccc;
    }

    .element:hover {
      // 鼠标放上去的时候，项目会放大 1.03 倍
      transform: scale(1.04);
    }

    img {
      width: 216px;
      height: 195px;
      border-radius: 5px;
      cursor: pointer;
    }

    .name {
      height: 30px;
      line-height: 30px;
      font-size: 16px;
      font-weight: 500;
      text-align: center;
    }
  }

  /** 左边 */
  .nav_left {
    float: left;
    width: 300px;
    background: #fff;
    box-shadow: 2px 7px 10px rgba(0, 0, 0, .08);
    -webkit-box-shadow: 0 0 10px rgba(0, 0, 0, .08);
    position: relative;
    margin-top: 20px;

    .sidenav_destination {
      background: #fff;
      border-radius: 4px 4px 4px 4px;
      border: 1px solid #f3f3f3;
      float: left;
      position: relative;
      z-index: 20;
      width: 300px;
    }

    .sidenav_destination .destination_col::before {
      content: '';
      width: 6px;
      height: 6px;
      background-color: $color-primary;
      left: 10px;
      top: 22px;
      position: absolute;
    }

    .sidenav_destination .destination_list {
      overflow: hidden;
      background-color: #fff;
    }

    .sidenav_destination .destination_list li {
      padding-left: 300px;
      position: relative;
      height: 50px;
      overflow: hidden;
      vertical-align: middle;
      zoom: 1;
      padding-left: 25px;
      margin: 0;
      background: #fff;
    }

    .sidenav_destination .destination_list li:hover {
      background-color: rgba(222,67,81, .09);
    }

    .sidenav_destination .destination_list .destination_col {
      overflow: hidden;
      margin-bottom: -1px;
      height: 50px;
      line-height: 50px;
    }

    .sidenav_destination .destination_list h3 {
      border-bottom: 1px #f3f3f3 solid;
      font-weight: 600;
      font-size: 18px;
      font-family: 'microsoft yahei', Arial, sans-serif !important;
      color: #333 !important;
    }

    .sidenav_destination .destination_list h4 {
      border-bottom: 1px #f3f3f3 solid;
      font-weight: 600;
      font-size: 16px;
      font-family: 'microsoft yahei', Arial, sans-serif !important;

      a {
        font-weight: 400;
        font-size: 16px;
        font-family: 'microsoft yahei', Arial, sans-serif !important;
        color: #535a6d !important;
        background: transparent;
        text-decoration: none;
        outline: none;
        cursor: pointer;
        transition: color 0.2s ease;

        :hover {
          color: $color-primary !important;
        }
      }
    }

    .sidenav_destination .destination_list p {
      overflow: hidden;
      zoom: 1;
      margin-left: -6px;
    }
  }

}
</style>
